import plugin from '../../../lib/plugins/plugin.js'
import { Config, Render, Version } from '../components/index.js'
import lodash from 'lodash'

let keys = lodash.map(Config.getCfgSchemaMap(), (i) => i.key)
let sysCfgReg = new RegExp(`^#?银趴设置\\s*(${keys.join('|')})?\\s*(.*)$`)
const groupReg = '^#?(获取|删除|添加)?(开始|结束)?银趴(禁用群|启用群)?([0-9]*)$'

export class setting extends plugin {
    constructor() {
        super({
            name: '[impart-pro-plugin] 设置',
            dsc: '[impart-pro-plugin] 设置',
            event: 'message',
            priority: 1,
            rule: [
                {
                    reg: sysCfgReg,
                    fnc: 'setting',
                    permission: 'master'
                },
                {
                    reg: groupReg,
                    fnc: 'modifyGroup'
                }
            ]
        })
    }

    async modifyGroup() {
        let reg = new RegExp(groupReg)
        let regRet = reg.exec(this.e.msg)
        if (!regRet) {
            return true
        }
        const type = regRet[3] ||  regRet[2]
        const target = type == ('禁用群' || '结束')  ? 'noImpart' : 'yesImpart'
        const cfg = {
            noImpart: Config.noImpart,
            yesImpart: Config.yesImpart
        }
        let group_id
        if(regRet[4] && this.e.isMaster) {
            group_id = regRet[4]
        } else if (regRet[4] && !this.e.isMaster) {
            this.e.reply(`达咩，你不是主人，其他群你不能管`)
            return false
        } else {
            group_id = this.e.group_id
        }
        let sendMsg = []
        if (regRet[1] && regRet[3] && this.e.isMaster) {
            switch (regRet[1]) {
                case '获取':
                    if (Array.isArray(cfg[target]) && cfg[target].length > 0) {
                        sendMsg.push(`以下为${type}群聊的群号\n`)
                        sendMsg.push(cfg[target].join('\n'))
                    } else {
                        sendMsg.push(`暂无${type}群聊`)
                    }
                    break;
                case '删除':
                    let index = -1
                    if (Array.isArray(cfg[target]) && cfg[target].length > 0) {
                        for (let i = 0; i < cfg[target].length; i++) {
                            if (cfg[target][i] == group_id) {
                                index = i
                            }
                        }
                    }
                    if (index == -1) {
                        sendMsg.push(`操作失败~在${type}群中没有这个群聊,当前${type}群列表:\n`)
                        sendMsg.push(cfg[target].join('\n'))
                    } else {
                        cfg[target].splice(index, 1)
                        sendMsg.push(`操作成功~从${type}群中删除了[${group_id}]!\n当前${type}列表:\n`)
                        sendMsg.push(cfg[target].join('\n'))
                    }
                    break;
                case '添加':
                    let isExist = false
                    if (Array.isArray(cfg[target]) && cfg[target].length > 0) {
                        for (const item of cfg[target]) {
                            if (item == group_id) {
                                isExist = true
                                break
                            }
                        }
                    } else {
                        cfg[target] = []
                    }
                    if (isExist) {
                        sendMsg.push(`操作失败~${type}群中已经添加了[${group_id}]\n当前${type}群列表:\n`)
                        sendMsg.push(cfg[target].join('\n'))
                    } else {
                        cfg[target].push(group_id)
                        sendMsg.push(`操作成功~向${type}群中添加了[${group_id}]!\n当前${type}群列表:\n`)
                        sendMsg.push(cfg[target].join('\n'))
                    }
                default:
                    break
            }
        } else if((regRet[2]) && (this.e.sender.role == 'owner' || this.e.sender.role == 'admin' || this.e.isMaster)) {
            let isExist = false
            switch (type) {
                case '结束':
                    // 先看白名单有没有这个群
                    if (Array.isArray(cfg['yesImpart']) && cfg['yesImpart'].length > 0) {
                        for (const i of cfg['yesImpart']) {
                            if (i == group_id) {
                                isExist = true
                            }
                        }
                    }
                    // 如果在白名单中则删除白名单
                    if (isExist) {
                        cfg['yesImpart'] = cfg['yesImpart'].filter(i => i != group_id)
                        sendMsg.push(`操作成功~从白名单中删除了[${group_id}]!`)
                    }
                    // 否则添加为黑名单 
                    else {
                        // 再看看黑名单有没有这个群
                        if (Array.isArray(cfg['noImpart']) && cfg['noImpart'].length > 0) {
                            for (const item of cfg['noImpart']) {
                                if (item == group_id) {
                                    isExist = true
                                    break
                                }
                            }
                        } else {
                            cfg['noImpart'] = []
                        }
                        if (isExist) {
                            sendMsg.push(`操作失败~黑名单中已经添加了[${group_id}]`)
                        } else {
                            cfg['noImpart'].push(group_id)
                            sendMsg.push(`操作成功~向黑名单中添加了[${group_id}]!`)
                        }
                    }
                    break
                case '开始':
                    // 先看黑名单有没有这个群
                    if (Array.isArray(cfg['noImpart']) && cfg['noImpart'].length > 0) {
                        for (const item of cfg['noImpart']) {
                            if (item == group_id) {
                                isExist = true
                                break
                            }
                        }
                    } else {
                        cfg['noImpart'] = []
                    }
                    // 如果在黑名单中则删除黑名单
                    if (isExist) {
                        cfg['noImpart'] = cfg['noImpart'].filter(i => i != group_id)
                        sendMsg.push(`操作成功~从黑名单中删除了[${group_id}]!`)
                    }
                    // 否则添加为黑名单 
                    else {
                        // 再看看白名单有没有这个群
                        if (Array.isArray(cfg['yesImpart']) && cfg['yesImpart'].length > 0) {
                            for (const item of cfg['yesImpart']) {
                                if (item == group_id) {
                                    isExist = true
                                    break
                                }
                            }
                        } else {
                            cfg['yesImpart'] = []
                        }
                        if (isExist) {
                            sendMsg.push(`操作失败~白名单中已经添加了[${group_id}]!`)
                        } else {
                            cfg['yesImpart'].push(group_id)
                            sendMsg.push(`操作成功~向白名单中添加了[${group_id}]!`)
                        }
                    }
                    break
                default:
                    break
            }
        } else return true
        try {
            for (const key in cfg) {
                Config.modify('impart-config', key, cfg[key])
            }
        } catch (error) {
            sendMsg = ['操作失败...']
            logger.error(error)
        }
        if(sendMsg.length>0) this.reply(sendMsg)
    }

    async setting(e) {
        let cfgReg = sysCfgReg
        let regRet = cfgReg.exec(e.msg)
        let cfgSchemaMap = Config.getCfgSchemaMap()
        if (!regRet) {
            return true
        }

        if (regRet[1]) {
            // 设置模式
            let val = regRet[2] || ''
            let cfgSchema = cfgSchemaMap[regRet[1]]
            if (cfgSchema.input) {
                val = cfgSchema.input(val)
            } else {
                val = cfgSchema.type === 'num' ? (val * 1 || cfgSchema.def) : !/关闭/.test(val)
            }
            if (val < 10) {
                this.reply('不能小于10'); // 回复用户
                return false
            } else {
                Config.modify(cfgSchema.fileName, cfgSchema.cfgKey, val)
            }
        }

        let schema = Config.getCfgSchema()
        let cfg = Config.getCfg()
        let imgPlus = false

        // 渲染图像
        return await Render.render('admin/index', {
            schema,
            cfg,
            imgPlus,
            isMiao: Version.isMiao
        }, { e, scale: 1.4 })
    }
}